package com.elitel.common.kudu;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class KuduClientPoolFactory implements PooledObjectFactory<KuduClient> {
    private Logger logger = LogManager.getLogger(KuduClientPoolFactory.class);
    private String masterAddress ;
    private long operationTimeoutMs ;

    public KuduClientPoolFactory(String masterAddress, long operationTimeoutMs ){
        this.masterAddress = masterAddress;
        this.operationTimeoutMs = operationTimeoutMs;
    }

    public PooledObject<KuduClient> makeObject() {
        KuduClient client = new KuduClient.KuduClientBuilder(masterAddress)
                .defaultAdminOperationTimeoutMs(operationTimeoutMs)
                .defaultOperationTimeoutMs(operationTimeoutMs)
                .build();
        logger.info("创建Kudu客户端连接成功");
        return new DefaultPooledObject<KuduClient>(client);
    }

    public void destroyObject(PooledObject<KuduClient> pooledObject) {
        KuduClient kuduClient = pooledObject.getObject();
        try {
            kuduClient.close();
            logger.info("Kudu客户端连接已关闭");
        } catch (KuduException e) {
            e.printStackTrace();
        }
    }

    public boolean validateObject(PooledObject<KuduClient> arg0) {
        return true;
    }

    public void activateObject(PooledObject<KuduClient> arg0) {
    }

    public void passivateObject(PooledObject<KuduClient> arg0) {
    }
}
